import java.util.LinkedHashMap;
import java.util.Map;



//基于已有的LinkedHashMap,重写方法来进行实现
public class LRUCache extends LinkedHashMap<Integer, Integer> {

    public int capacity;
    public LRUCache(int capacity) {
        //这个的true  代表 基于访问顺序
        super(capacity,0.75F,true);
        this.capacity = capacity;
    }

    @Override
    public Integer get(Object key) {
        return super.getOrDefault(key,-1);
    }

    @Override
    public Integer put(Integer key, Integer value) {
        return super.put(key, value);
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
        return size() > capacity;
    }


    public static void main(String[] args) {
        LRUCache lruCache = new LRUCache(3);
        lruCache.put(100,10);
        lruCache.put(110,11);
        lruCache.put(120,12);
        System.out.println(lruCache);
        System.out.println("获取元素");
        System.out.println(lruCache.get(110));
        System.out.println(lruCache);
        System.out.println(lruCache.get(100));
        System.out.println(lruCache);

        System.out.println("存放元素,会删除头节点，因为头节点是最近最少使用的: ");
        lruCache.put(999,99);

        System.out.println(lruCache);

    }

    public static void main3(String[] args) {
        LinkedHashMap<String,Integer> linkedHashMap =
                new LinkedHashMap<>(16,0.7f,true);
        linkedHashMap.put("高博",10);
        linkedHashMap.put("abcd",11);
        linkedHashMap.put("hello",12);
        System.out.println(linkedHashMap);
        System.out.println("获取元素");
        System.out.println(linkedHashMap.get("abcd"));
        System.out.println(linkedHashMap);
        System.out.println(linkedHashMap.get("高博"));
        System.out.println(linkedHashMap);

    }



    //是基于插入顺序
    public static void main1(String[] args) {
        LinkedHashMap<String,Integer> linkedHashMap =
                new LinkedHashMap<>(16,0.7f,false);
        linkedHashMap.put("高博",10);
        linkedHashMap.put("abcd",11);
        linkedHashMap.put("hello",12);
        System.out.println(linkedHashMap);
        System.out.println("获取元素");
        System.out.println(linkedHashMap.get("abcd"));
        System.out.println(linkedHashMap);
    }
}
